package com.main.controller;

import com.google.gson.Gson;
import com.main.common.Response;
import com.main.util.EncryptionUtil; // 假设这是您的加密工具类
import org.springframework.stereotype.Controller;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;



@Controller
public abstract class BaseController {

    private static final Gson GSON = new Gson();

    protected void streamJsonData(HttpServletResponse response, Object data) throws IOException {
        String json = GSON.toJson(Response.success(data));
        byte[] jsonData;
        try {
            jsonData = json.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Failed to encode JSON data", e);
        }

        try {
            // 加密数据
            byte[] encryptedData = EncryptionUtil.encrypt(jsonData).getBytes(); // 移除 .getBytes() 调用，因为 encrypt 方法应该返回 byte[]

            // 设置响应头
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setContentLength(encryptedData.length);

            // 获取输出流并写入数据
            try (OutputStream out = response.getOutputStream()) {
                out.write(encryptedData);
                out.flush(); // 确保数据立即发送到客户端
            }
        } catch (Exception e) {
            // 处理加密过程中可能出现的异常
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            try (OutputStream out = response.getOutputStream()) {
                out.write("加密过程中发生错误".getBytes("UTF-8"));
            }
        }
    }
}